package com.example.imoocmall.service.impl;

import com.example.imoocmall.common.Constant;
import com.example.imoocmall.exception.ImoocMallException;
import com.example.imoocmall.exception.ImoocMallExceptionEnum;
import com.example.imoocmall.filter.UserFilter;
import com.example.imoocmall.model.dao.OrderMapper;
import com.example.imoocmall.model.pojo.Order;
import com.example.imoocmall.model.vo.OrderVo;
import com.example.imoocmall.service.OrderAdminService;
import com.example.imoocmall.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderAdminServiceImpl implements OrderAdminService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderService orderService;

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize,"create_time"+" "+"desc");
        List<Order> orderAll = orderMapper.selectAllOrder();

        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orderAll.size(); i++) {
            Order order =  orderAll.get(i);
            OrderVo orderVo = orderService.detail(order.getOrderNo());
            orderVoList.add(orderVo);
        }
        PageInfo pageInfo = new PageInfo(orderVoList);
        return pageInfo;
    }

    @Override
    public void delivered(String orderNo){
        Order order = orderMapper.selectByOrderNo(orderNo);
        //判断订单存不存在
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NO_ORDER);
        }
        if (order.getOrderStatus() == Constant.OrderStatusEnum.PAID.getCode()){
            order.setOrderStatus(Constant.OrderStatusEnum.DELIVERED.getCode());
            order.setDeliveryTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else {
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_DELIVERED);
        }
    }
}
